package com.scorpio.baselibrary.adapter;

import android.view.View;
import android.view.ViewGroup;

import androidx.viewpager.widget.PagerAdapter;

import com.scorpio.baselibrary.ScreenAdapterTools;
import com.scorpio.baselibrary.utils.ViewController;

import java.util.LinkedList;
import java.util.List;

/**
 * created by 包子 on 2018/12/13
 */
public abstract class BasicPagerAdapter extends PagerAdapter {
    /**
     * 已经销毁的Item，存起来复用
     */
    private final List<ViewController> mRecyclerList = new LinkedList<>();
    /**
     * 正在使用的Item， 存起来以便可以定点刷新
     */
    private final List<ViewController> mUsedList = new LinkedList<>();

    @Override
    public void notifyDataSetChanged() {
        mRecyclerList.clear();
        mUsedList.clear();
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ViewController) object).getLayoutView();
    }

    @Override
    public int getItemPosition(Object object) {
        //1、如果列表为空，直接返回POSITION_NONE， 防止移除时不能刷新
        //2、如果下标越界，直接返回POSITION_NONE
        //3、根据子类isViewHolderChanged返回值 决定是否返回POSITION_NONE
        //如果返回POSITION_NONE 将会重新instantiateItem
        if (getCount() == 0 || ((ViewController) object).getPosition() >= getCount() || isViewHolderChanged((ViewController) object)) {
            return POSITION_NONE;
        }
        return POSITION_UNCHANGED;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ViewController holder;
        if (!mRecyclerList.isEmpty()) {//是否有可复用的item
            holder = mRecyclerList.remove(0);
        } else {//新建item
            View view = onCreateView(container);
            ScreenAdapterTools.getInstance().loadView(view);
            holder = new ViewController(container.getContext(), view);
        }
        holder.setPosition(position);
        //绑定item数据
        onBindView(holder, position);
        container.removeView(holder.getLayoutView());
        container.addView(holder.getLayoutView());
        mUsedList.add(holder);
        return holder;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ViewController holder = (ViewController) object;
        container.removeView(holder.getLayoutView());
        mUsedList.remove(holder);
        mRecyclerList.add(holder);
    }

    public List<ViewController> getUsedHolders() {
        return mUsedList;
    }

    public abstract View onCreateView(ViewGroup container);

    public abstract void onBindView(ViewController holder, int position);

    public abstract boolean isViewHolderChanged(ViewController holder);
}